<template>
  <div>
    <div v-for="(item, index) in addform" :key="index">
      <!--根据componentType来显示是什么标签-->
      <!--输入框-->
      <el-input
        v-if="item.componentType === 'el-input'"
        size="small"
        style="width: 100%"
        v-model="form[item.prop]"
        :disabled="disabled || !item.editable"
        :placeholder="item.placeholder"
      >
      </el-input>
      <template v-else-if="item.componentType === 'el-clear'">
        {{ form[item.prop] }}
        <el-button
          icon="el-icon-delete"
          circle
          @click="form[item.prop] = null"
          v-if="form[item.prop]"
        ></el-button>
        <!-- <el-button size="mini" type="plain" icon="el-icon-circle-close"></el-button> -->
      </template>
      <!--选择框-->
      <el-select
        size="small"
        style="width: 100%"
        v-model="form[item.prop]"
        placeholder="请选择"
        v-else-if="item.componentType === 'el-select'"
        :disabled="disabled || !item.editable"
        clearable
        filterable
      >
        <el-option
          v-for="dict in item.optionValue"
          :key="dict.id"
          :label="dict.systemName || !dict.name ? dict.description : dict.name"
          :value="
            typeof form[item.prop] == 'number'
              ? Number(dict.id)
              : String(dict.id)
          "
        >
        </el-option>
      </el-select>
      <!--多选 选择框-->
      <el-select
        multiple
        size="small"
        style="width: 100%"
        v-model="form[item.prop]"
        placeholder="请选择"
        v-else-if="item.componentType === 'el-selects'"
        @change="handleSelectChange"
        :disabled="disabled || !item.editable"
        filterable
      >
        <el-option
          v-for="dict in item.optionValue"
          :key="dict.id"
          :label="dict.systemName || !dict.name ? dict.description : dict.name"
          :value="dict.id"
        >
        </el-option>
      </el-select>
      <!--级联选择器-->
      <el-cascader
        size="small"
        style="width: 100%"
        v-else-if="item.componentType === 'el-cascader'"
        v-model="form[item.prop]"
        :options="item.optionValue"
        :disabled="disabled || !item.editable"
        :props="{ expandTrigger: 'hover', emitPath: false }"
      >
      </el-cascader>
      <!-- 年月 -->
      <el-date-picker
        v-model="form[item.prop]"
        format="yyyy-MM"
        value-format="yyyy-MM"
        placeholder="请选择年月"
        clearable
        v-else-if="item.componentType === 'el-month-picker'"
        type="month"
        :picker-options="
          form.id == undefined && item.optionValue ? pickerOptions : ''
        "
      >
      </el-date-picker>
      <!--日期-->
      <el-date-picker
        v-model="form[item.prop]"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        placeholder="请选择日期"
        clearable
        v-else-if="item.componentType === 'el-date-picker'"
        :disabled="disabled || !item.editable"
        :picker-options="
          form.id == undefined && item.optionValue ? pickerOptions : ''
        "
      >
      </el-date-picker>
      <!--多选日期-->
      <el-date-picker
        style="width: 100%"
        type="dates"
        v-model="form[item.prop] ? form[item.prop].split(',') : form[item.prop]"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        placeholder="请选择日期"
        clearable
        :disabled="disabled || !item.editable"
        v-else-if="item.componentType === 'el-dates-picker'"
      >
      </el-date-picker>
      <!--日期范围-->
      <el-date-picker
        style="width: 100%"
        v-model="form[item.prop] ? form[item.prop].split(',') : form[item.prop]"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :disabled="disabled || !item.editable"
        v-else-if="item.componentType === 'el-dates-daterange'"
      >
      </el-date-picker>
      <!--单选框-->
      <el-radio-group
        :disabled="disabled || !item.editable"
        v-model="form[item.prop]"
        v-else-if="item.componentType === 'el-radio'"
      >
        <el-radio
          v-for="dict in item.optionValue"
          :key="dict.id"
          :label="Number(dict.id)"
          >{{ dict.description }}
        </el-radio>
      </el-radio-group>
      <!--多选框-->
      <div v-else-if="item.componentType === 'el-checkbox-group'">
        <div style="margin-left: 20px">文档名称</div>
        <el-checkbox-group v-model="docIds" style="max-height: 300px">
          <el-checkbox
            style="display: block"
            v-for="val in item.optionValue"
            :label="Number(val.id)"
            :key="val.id"
            >{{ val.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <!--添加现有项-->
      <template v-else-if="item.componentType === 'el-add-existing'">
        <el-select
          size="small"
          style="width: calc(95% - 50px);height:100%"
          v-model="form[item.prop]"
          placeholder="请选择"
          :disabled="true"
          filterable
        >
          <el-option
            v-for="dict in item.optionValue"
            :key="dict.id"
            :label="dict.name || dict.folderName"
            :value="String(dict.id)"
          >
          </el-option>
        </el-select>
        <el-button
          style="width: 50px; margin: 5px 0;"
          size="mini"
          :disabled="disabled || !item.editable"
          @click="addExisting(item)"
        >
          选择
        </el-button>
      </template>
      <!-- 评分 -->
      <el-rate
        v-else-if="item.componentType === 'el-rate'"
        style="margin-top: 10px"
        v-model="form[item.prop]"
        show-score
        :disabled="disabled || item.status != '1'"
        text-color="#ff9900"
      >
      </el-rate>
    </div>
    <el-dialog
      ref="formTable"
      :title="title"
      :visible.sync="topen"
      width="80%"
      v-dialogDrag
      append-to-body
      :close-on-click-modal="false"
      v-if="topen"
    >
      <dynamic-form-table
        ref="addFormTable"
        :geturl="geturl"
        @topenChanged="topenChanged"
        @submit="handleSubmitAddExisting"
        :table="table"
        :formtype="formtype"
        :search="search"
        :formMulti="formMulti"
        :defaultSelect="defaultSelect"
        :expandUrl="expandUrl"
      >
      </dynamic-form-table>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addData, updateData, getDataList } from '@/api/dynamic/dynamic'
import { deepClone } from '@/utils'
import { uploadObj } from '@/settings.js'
export default {
  name: 'dynamicFormItem',
  props: {
    form: Object,
    addform: Array,
    disabled: false
  },
  components: {
    dynamicFormTable: () => import('@/views/components/dynamicFormTable')
  },
  data() {
    return {
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/common/upload",
        url: uploadObj.upload,
        // 上传的文件列表
        showFileList: [],
        // 大小限制(MB)
        fileSize: 200
      },
      docIds: [],
      current: null,
      topen: false,
      geturl: '',
      formMulti: 'false',
      search: 'full_search',
      table: 'table',
      formtype: '',
      defaultSelect: {},
      title: '',
      expandUrl: ''
    }
  },
  watch: {
    addform: {
      //监听的对象
      deep: true, //深度监听设置为 true
      immediate: true,
      handler: function() {
        this.getOptionsData()
      }
    },
    'form.typeid': {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        if (newV != undefined && newV != oldV) {
          this.handleChange(newV, oldV)
        }
      }
    },
    'form.policyid': {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        if (newV != undefined && newV != oldV) {
          this.selectChange(newV, oldV)
        }
      }
    }
  },
  created() {
    // this.getOptionsData();
  },
  methods: {
    handleFileBeforeUpload(file) {
      if (this.upload.fileType) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.upload.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确, 请上传${this.upload.fileType.join('/')}格式文件!`
          )
          return false
        }
      }
      // 校检文件大小
      if (this.upload.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.upload.fileSize
        if (!isLt) {
          this.$message.error(
            `上传文件大小不能超过 ${this.upload.fileSize} MB!`
          )
          return false
        }
      }
      return true
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`文件个数超出限制`)
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error('上传失败, 请重试')
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      if (!this.form.hasOwnProperty('fileList')) {
        this.form.fileList = []
      }
      this.form.fileList.push({
        fileName: file.name,
        path: response.fileName,
        fileSize: file.size
      })
      this.msgSuccess(response.msg)
    },
    getOptionsData() {
      let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
      this.addform.forEach((item, index) => {
        if (
          item.componentType === 'el-select' ||
          item.componentType === 'el-radio' ||
          item.componentType === 'el-checkbox-group'
        ) {
          if (
            item.prop === 'policyid' ||
            item.prop === 'stateid' ||
            item.prop === 'ownerid'
          ) {
            if (typeof item.optionValue == 'string') {
              this.addform[index].optionValue = optionData[item.optionValue]
            }
          } else {
            if (!Array.isArray(item.optionValue))
              if (
                this.tempDicts[item.prop] &&
                this.tempDicts[item.prop].length > 0
              ) {
                // this.getDicts(item.optionValue).then((response) => {
                //   this.addform[index].optionValue = this.selectNormalizer(
                //     response.data
                //   );
                // });
                this.addform[index].optionValue = this.selectNormalizer(
                  deepClone(this.tempDicts[item.prop])
                )
              } else if (!Array.isArray(item.optionValue)) {
                if (item.optionValue && item.optionValue.indexOf('url') > -1) {
                  let url = this.getUrl(item.optionValue.split(':')[1])
                  getDataList(url).then(response => {
                    if (response.code == 200) {
                      this.addform[index].optionValue = response.rows
                    }
                  })
                } else {
                  this.getDicts(item.optionValue).then(response => {
                    this.tempDicts[item.prop] = deepClone(response.data)
                    this.addform[index].optionValue = this.selectNormalizer(
                      response.data
                    )
                  })
                }
              }
          }
        }
        if (item.componentType === 'el-cascader') {
          if (typeof item.optionValue == 'string') {
            let optionarr = item.optionValue.split('?')
            if (optionarr.length > 1) {
              this.normalizer(optionData[optionarr[0]])
              let typearr = []
              optionData[optionarr[0]].forEach(titem => {
                if (titem.value === parseInt(optionarr[1])) {
                  typearr.push(titem)
                  this.addform[index].optionValue = typearr
                }
              })
            } else {
              this.addform[index].optionValue = this.normalizer(
                optionData[item.optionValue]
              )
            }
          }
        }
        if (item.componentType === 'el-checkbox-group') {
          getDataList(item.optionValue, {}).then(response => {
            this.addform[index].optionValue = []
            this.addform[index].optionValue = response.rows
          })
        }
      })
      this.$forceUpdate()
    },
    /** 转换数据结构 */
    normalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          value: item.id,
          label: item.description,
          parentid: item.parentid
        }
      })
      return this.handleTree(data, 'value')
    },
    /** 转换选项数据结构 */
    selectNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          id: item.dictValue,
          description: item.dictLabel
        }
      })
      return data
    },
    // 取消按钮
    cancel() {
      this.$emit('openChanged', false)
    },
    /** 提交按钮 */
    submitForm() {
      var route = this.addurl
      if (route) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.docIds.length > 0) {
              this.form.docIds = this.docIds.join(',')
            }
            if (this.form.id != undefined) {
              updateData(route, this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.$emit('openChanged', true)
                }
              })
            } else {
              addData(route, this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.$emit('openChanged', true)
                }
              })
            }
          }
        })
      } else {
        this.msgError('缺少链接！')
      }
    },
    handleChange(newV, oldV) {
      if (newV != undefined) {
        let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
        let policyObj = optionData['policyOptions']
        let policyOptions = []
        policyObj.forEach(item => {
          if (item.typeIds) {
            if (item.typeIds.split(',').includes(newV.toString())) {
              policyOptions.push(item)
            }
          }
        })
        this.addform.forEach((item, index) => {
          if (item.prop === 'policyid') {
            if (oldV) {
              this.form.policyid = ''
              this.form.stateid = ''
            }
            this.addform[index].optionValue = policyOptions
            if (policyOptions.length == 1) {
              this.form.policyid = policyOptions[0].id
            }
          }
        })
      }
    },
    selectChange(newV, oldV) {
      let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
      let policyObj = optionData['policyOptions']
      if (!this.form.revision) {
        policyObj.forEach(item => {
          if (item.id === newV) {
            this.form.revision = item.revision
          }
        })
      }
      let stateObj = optionData['stateOptions']
      let stateOptions = []
      stateObj.forEach(item => {
        if (item.policyid === newV) {
          stateOptions.push(item)
        }
      })
      this.addform.forEach((item, index) => {
        if (item.prop === 'stateid') {
          if (oldV) this.form.stateid = ''
          this.addform[index].optionValue = stateOptions
          if (!this.form.stateid) this.form.stateid = stateOptions[0].id
        }
      })
    },
    handleSelectChange(prop) {
      this.$forceUpdate()
      //  this.selectChange(val,'');
      for (let item of this.addform) {
        if (item.show && item.show.indexOf(prop) > -1) {
          getDataList(item.show.replace(`{${prop}}`, this.form[prop])).then(
            response => {
              if (response.code == 200) {
                item.optionValue = response.rows
              }
            }
          )
        }
      }
    },
    addExisting(item) {
      let pageParams = eval('(' + item.show + ')')
      this.table = pageParams.table
      this.formtype = pageParams.type
      // if(pageParams.defaultSelect){
      //   let arr = pageParams.defaultSelect.split('-');
      //   this.defaultSelect[arr[0]]=this.selected[0][arr[1]].split(',');
      // }else{
      //   this.defaultSelect = {}
      // }
      this.expandUrl = pageParams.expandUrl
      if (pageParams.search != undefined) this.search = pageParams.search
      this.geturl = this.getUrl(pageParams.getUrl)
      this.title = item.name
      this.current = item
      this.topen = true
      this.defaultSelect = { id: [this.form[item.prop]] }
      // console.log(this.form[item.prop])
      // this.geturl = item.show
      this.formMulti = pageParams.formMulti
    },
    topenChanged() {
      this.topen = false
    },
    handleSubmitAddExisting(val) {
      // console.log(val)
      // this.current.optionValue = val
      this.form[this.current.prop] = String(val.map(item => item.id)[0])
      // this.form[this.current.prop+"ShowName"] = val.map(item=>item.name)[0]
      this.topen = false
    }
  }
}
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
.el-checkbox.el-checkbox__label {
  width: 100%;
}
</style>
